package com.ruangong.GitClient.app;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.ruangong.GitClient.R;
import com.ruangong.GitClient.HunHePanAPI.Tab;
import com.ruangong.GitClient.HunHePanAPI.TabListAdapter;
import com.ruangong.GitClient.HunHePanAPI.getTab;
import java.util.ArrayList;
import java.util.List;

public class TabList extends Fragment {

    private ListView searchResultListView;
    private ArrayAdapter<Tab> adapter;
    private List<Tab> searchResults;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_tab_list, container, false);

        searchResultListView = rootView.findViewById(R.id.websiteListView);

        // 初始化搜索结果列表
        searchResults = new ArrayList<>();
        adapter = new TabListAdapter(getContext(), searchResults);

        searchResultListView.setAdapter(adapter);

        // 执行搜索操作
        performGetnew();

        // 设置列表项的点击事件
        searchResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取点击的项的内容
                Tab clickedTab = searchResults.get(position);
                // 创建跳转到另一个Activity的意图
                Intent intent = new Intent(getActivity(), TabSource.class);
                // 在Intent中传递额外的数据，如果需要的话
                intent.putExtra("TAB_MASSAGE", clickedTab);
                startActivity(intent);
            }
        });

        return rootView;
    }

    // 执行搜索操作
    private void performGetnew() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 在这里执行网络请求
                List<Tab> Tabs = getTab.getResult();
                searchResults.clear();
                if (Tabs == null || Tabs.isEmpty()) {
                    searchResults.add(new Tab("获取列表失败", 0)); // 添加一个标记项
                    searchResultListView.setOnItemClickListener(null);
                } else {
                    // 将搜索结果添加到 searchResults 列表中
                    searchResults.addAll(Tabs);
                }
                // 切换回主线程更新UI
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }
}
